
import * as jwt from 'jsonwebtoken';
import dTalkApi from '../core/dTalkApi';
import * as Router from 'koa-router';
import env from './../config/env'
import { IRouterContext } from 'koa-router';
import BPM from '../lib/db/BPM';
let router = new Router();
router.prefix('/api/auth');
//免登
router.get('/login', async (ctx: IRouterContext, next: any) => {
    let authCode: string = ctx.query.code;
    console.log('免登!!!!!!!','authCode:',authCode)
    let user=await dTalkApi.getUserInfo(authCode);
    let userJson:any=await dTalkApi.getUserDetail(user.userid);
    let jobnumber=userJson.jobnumber;
    let  GUID = await BPM.query({
        query: `select GUID from Ts_User where LoginName=?`,
        values: [`${jobnumber}`]
    });
    GUID=GUID[0];
    if(GUID.length>0){
       for (let index = 0; index < GUID.length; index++) {
           let element = GUID[index];
           GUID=element.GUID;
           break;
       }
    }
    console.log(GUID, 'GUID_GUID_GUID_GUID_GUID_');
    let guid2 = GUID ? GUID : '';
    //判断是否是门卫
    if(user){
        let token = jwt.sign({ userId: user.userid, is_sys: user.is_sys, jobnumber: userJson.jobnumber, name: userJson.name }, env.corpsecret);
        console.log(token,'token_token_token_token_')
        ctx.body = {
            token: `Bearer ${token}`, UserInfo: userJson,GUID: guid2
        };
    }else{//免登失败
        ctx.throw(401, '认证失败！');
    }
    await next();
});

//签名
router.get('/getPcJsConfig',async (ctx: IRouterContext, next: any)=>{
    console.log('-----sign------query...', ctx.querystring);
    let nonceStr = "abcd" + (Math.random() * 1000).toFixed(0);//签名随机数
    var timeStamp = Date.now();
    let url = `${env.domain}${ctx.querystring ? '?' + ctx.querystring : ''}`;//后期处理
    let signedUrl = decodeURIComponent(url);
    let signStr: string = await dTalkApi.getSign(nonceStr, timeStamp, signedUrl);
    let config = {
        agentId: '205473493', // 必填，微应用ID
        corpId: env.corpId,//必填，企业ID
        timeStamp: timeStamp, // 必填，生成签名的时间戳
        nonceStr: nonceStr, // 必填，生成签名的随机串
        signature: signStr, // 必填，签名
        type: 0   //选填。0表示微应用的jsapi,1表示服务窗的jsapi。不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
    };
    console.log(config,'config_config_');
    ctx.body = config;
    await next();
});

export default router


